/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {number[]}
 */
var findOrder = function(numCourses, prerequisites) {
    let res = new Array(numCourses).fill(0);
    let g = new Array(numCourses);
    for (let i = 0; i < numCourses; i++) {
        g[i] = new Set();
    }
    let indegrees = new Array(numCourses).fill(0);
    for (let i = 0; i < prerequisites.length; i++) {
        let w = prerequisites[i][0];
        let v = prerequisites[i][1];
        g[v].add(w);
        indegrees[w]++;
    }
    let queue = [];
    for (let i = 0; i < numCourses; i++) {
        if (indegrees[i] == 0) queue.push(i);
    }
    let index = 0;
    while (queue.length) {
        let v = queue.shift();
        res[index++] = v;
        for (let w of g[v]) {
            indegrees[w]--;
            if (indegrees[w] == 0) queue.push(w);
        }
    }
    return index == numCourses ? res : [];
};